import { useMqQueue } from "@sker/core";
import { Channel, ConsumeMessage } from "amqplib";

export class RedPacketMessageQueue {
    constructor(private c: Channel, private queue: string, private handleMessage: (msg: ConsumeMessage) => void) {
        this.get();
    }
    send(content: string) {
        return this.c.sendToQueue(this.queue, Buffer.from(content))
    }
    get() {
        this.c.consume(this.queue, (msg) => {
            this.handleMessage(msg)
        }, {
            noAck: false,
        })
    }
}

const queue = `RedPacket`;
useMqQueue(queue, async (c) => {
    return new Promise<void>((resolve, reject) => {
        new RedPacketMessageQueue(c, queue, (msg) => {
            
            c.ack(msg);
        })
        c.on('error', () => {
            reject()
        })
    })
})
